# pythonProject5/schemas/auth.py

from pydantic import BaseModel, EmailStr, Field, validator
from typing import Optional, Dict
from datetime import datetime


class LoginRequest(BaseModel):
    username: Optional[str] = Field(None, min_length=3, max_length=50)
    email: Optional[EmailStr] = None
    password: str = Field(..., min_length=6)
    
    @validator('email')
    def validate_email(cls, v, values):
        # 如果用户名为空且邮箱也为空，则抛出错误
        if not v and not values.get('username'):
            raise ValueError('必须提供用户名或邮箱')
        return v
        
    @validator('username')
    def validate_username(cls, v, values):
        # 如果用户名为空，确认邮箱字段存在于values中
        # 此验证器会先于email验证器运行，所以我们只需确保如果username为空，
        # values字典中包含email键（即使其值可能为None）
        if not v and 'email' not in values:
            raise ValueError('必须提供用户名或邮箱')
        return v


class RegisterRequest(BaseModel):
    username: Optional[str] = Field(None, min_length=3, max_length=50)
    email: EmailStr
    password: str = Field(..., min_length=6)


class TokenResponse(BaseModel):
    access_token: str
    refresh_token: str
    token_type: str
    expires_in: int
    user:Dict


class UserOut(BaseModel):
    id: int
    username: str
    email: str
    is_active: bool
    created_at: datetime  # 使用 datetime 类型

    @validator("created_at", pre=True, always=True)
    def format_created_at(cls, v):
        if isinstance(v, str):
            return datetime.strptime(v, "%Y-%m-%dT%H:%M:%S.%f%z")  # 转换为 datetime 类型
        return v

    class Config:
        from_attributes = True
